<template>
  <div class="city-select">
    <div>
      <h5Pop
        ref="h5PopFrame"
        poptypes="shitang"
        :h5pop="isShowH5Pop"
        @cancel="isShowH5Pop = false"
      />
    </div>
    <div class="scroll-container" style="height: 100%; overflow-y: auto">
      <!-- 滚动内容 -->
      <div class="search-header">
        <div class="location">
          <div class="search-content">
            <van-search
              v-model="searchValue"
              class="search-input"
              shape="round"
              placeholder="您可以直接输入定位名称"
              fontsize="14px"
              @input="handleInput"
            >
              <div slot="action" @click="handleClear()">取消</div>
            </van-search>
          </div>
        </div>
      </div>
      <div class="enterprise-list-header">
        <div class="view-location">
          <div class="location-header">当前定位城市</div>
          <div class="location-list">
            <div
              class="location-item"
              @click="onCurrentCityClick(cityName, $event)"
            >
              <img
                class="location-img"
                src="@/assets/serviceList/location.png"
              >
              {{ cityName }}
            </div>
          </div>
        </div>
        <div v-if="historyCity.length > 0" class="view-location">
          <div class="location-header">历史选择</div>
          <div class="location-list">
            <div
              v-for="(item, index) in historyCity"
              :key="index"
              class="location-item"
              @click="onCityClick(item, $event)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
        <ul class="list-alphabet">
          <li
            v-for="(word, index) in alphabet"
            :key="index"
            class="item"
            @click="onAlphabetClick(word, index)"
          >
            {{ word }}
          </li>
        </ul>
        <div>
          <div ref="cityList" class="city-list">
            <div
              v-for="(item, index) in sortList"
              :id="'city-' + item.letter"
              :key="index"
            >
              <div>
                <div slot="header" class="city-header">
                  {{ item.letter }}
                </div>
                <div
                  v-for="(project, i) in item.data"
                  :key="i"
                  class="city-item"
                >
                  <div @click="onCityClick(project, $event)">
                    {{ project.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCityList } from '@/api/h5'
import h5Pop from '@/components/h5Pop/h5Pop'
import { pySortByList } from '@/utils/util.js' // 导入工具类
import { Toast } from 'vant'

export default {
  components: {
    h5Pop
  },
  data() {
    return {
      saveTime: 5, // 缓存时间，单位分钟
      searchValue: '',
      toView: '',
      scrollTop: 0,
      city: '',
      cityCode: '',
      cityName: '',
      hotCity: [],
      cityList: [],
      sortList: [],
      alphabet: [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ],
      historyCity: [],
      isShowH5Pop: false
    }
  },
  created(query) {
    Toast.loading({
      duration: 0, // 持续展示 toast
      message: '处理中...'
    })
    if (window.AlipayJSBridge) {
      window.AlipayJSBridge.call('setTitle', {
        title: '城市选择'
      })
    } else {
      document.addEventListener(
        'AlipayJSBridgeReady',
        () => {
          window.AlipayJSBridge.call('setTitle', {
            title: '城市选择'
          })
        },
        false
      )
    }

    const historyCityList = JSON.parse(localStorage.getItem('historyCity'))
    if (historyCityList) {
      // 清除历史记录中的空数据
      const oldHistory = historyCityList
      const newHistory = []
      for (let i = 0; i < oldHistory.length; i++) {
        if (oldHistory[i] != null) {
          newHistory.push(oldHistory[i])
        }
      }
      this.historyCity = newHistory
    }
    if (localStorage.getItem('locationPermission')) {
      this.cityName = '定位失败'
      this.getCityList()
    } else {
      this.getLocationJSAPINew()
    }
  },
  mounted(query) {
    this.isShowH5Pop = false
    document.addEventListener('visibilitychange', this.handleVisibilityChange)

    if (window && window.AlipayJSBridge) {
      const _this = this
      AlipayJSBridge.call('setOptionMenu', {
        icon: 'iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAUKADAAQAAAABAAAAUAAAAAAx4ExPAAABn0lEQVR4Ae3XwW3CQBCFYdapwsecudkdRCmDW5IrFSW3lBHRgX2jhMhlODMWlvZiNE9ZS6z0r4Qwy2N2/YFhOBwYCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIlBRIWbHUdd17SunN5o63+es8z1/jOH7a4znL7nlY1T4WwL7vWxP5ttvLhszF5k/DMEwbzxeZrnEfjZ25I97DcxyH9Uz+ifX5kqPKfTzZZfthl+05IPHctu3vNE1jICtHat1Hc/vOC52wkg0VzEJKbSWbLRE6VGp71i/h9QcjsoCSjdTLM0ptJZuvETlWah8dkPEPAQe8Cq9XskLZJarUVrK77qPxPi+6gpKN1lxzSm0lu9aP3iu1PeutQ7L+68fuvVW5Ny7WB75aYK+Gusp9+CXsICe7ebO8NZZG2p7cC8/XrXIfeWNc1V+orXe64PyjeBQ8JUohgAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCDy+wB97bJ5UeONBvgAAAABJRU5ErkJggg=='
      })
      AlipayJSBridge.call('showOptionMenu')
      document.addEventListener(
        'optionMenu',
        function(e) {
          _this.isShowH5Pop = true
        },
        false
      )
    }
    const historyCityList = JSON.parse(localStorage.getItem('historyCity'))
    if (historyCityList) {
      // 清除历史记录中的空数据
      const oldHistory = historyCityList
      const newHistory = []
      for (let i = 0; i < oldHistory.length; i++) {
        if (oldHistory[i] != null) {
          newHistory.push(oldHistory[i])
        }
      }
      this.historyCity = newHistory
    }
    // this.getCityList()
  },
  methods: {
    async getCityList() {
      // console.log(this.searchValue)
      const data = {
        name: this.searchValue
      }
      await getCityList(data)
        .then((res) => {
          console.log(res, 'res')
          this.cityList = res
          // console.log(this.cityList);
          this.sortList = pySortByList(this.cityList)
          console.log(this.sortList, 'this.sortList')
          Toast.clear()
        })
        .catch((err) => {
          // console.log(err);
          Toast.clear()
          Toast.loading({
            duration: 1000 * 2,
            message: '系统繁忙，请稍后再试'
          })
        })
    },
    scrollEnd() {},
    scrollToTop(e) {
      this.scrollTop = 0
    },
    onAlphabetClick(item, index) {
      console.log(item, index)
      const targetId = `city-${item}`
      const target = this.$refs.cityList.querySelector(`#${targetId}`)
      if (target) {
        target.scrollIntoView({
          behavior: 'smooth'
        })
      }
      console.log(item, index)
    },
    handleInput(searchValue) {
      this.searchValue = searchValue
      this.getCityList()
    },
    handleClear() {
      this.searchValue = ''
      this.getCityList()
    },
    getLocationJSAPINew(isRetryLocationPermission = true) {
      console.log('调用定位api222')
      const _this = this
      window.AlipayJSBridge &&
        window.AlipayJSBridge.call('location', {}, function(result) {
          const res = result
          console.log(res, 'res获取222')
          // 获取用户当前位置省市信息
          if (res.error) {
            // 定位失败 获取定位信息
            _this.cityName = '定位失败'
            _this.getCityList()
            if (!isRetryLocationPermission || localStorage.getItem('locationPermission')) {
              // 定位失败且申请
            } else {
              _this.getLocation()
            }
          } else {
            // 定位成功
            let cityCode = Number(res.adCode)
            cityCode = parseInt(cityCode / 100) * 100
            _this.cityName = res.city
            _this.city = res.city
            _this.cityCode = cityCode
            localStorage.removeItem('locationPermission')
            _this.getCityList()
          }
        })
    },
    getLocation() {
      const _this = this
      if (window.AlipayJSBridge) {
        AlipayJSBridge.call('check_location_permission', function(result) {
          console.log(result, '获取hasLocationPermission')
          if (result.hasLocationPermission == 1) {
            // 有定位权限
            _this.getLocationJSAPINew(false)
          } else {
            // 没有定位权限
            localStorage.setItem('locationPermission', true)
            AlipayJSBridge.call(
              'request_location_permission',
              function(result) {
                if (
                  _this.deviceType == 'HarmonyOS' ||
                  _this.deviceType == 'Android'
                ) {
                  console.log(
                    result.requestPermissionResult,
                    'HarmonyOS_Android_requestLocationPermission'
                  )
                  if (result.requestPermissionResult == 'granted') {
                    _this.getLocationJSAPINew()
                  }
                } else {
                  console.log(
                    result.requestPermissionResult,
                    'IOS_requestLocationPermission'
                  )
                  if (
                    result.requestPermissionResult == 'already_have_permission'
                  ) {
                    _this.getLocationJSAPINew()
                  }
                }
              }
            )
          }
        })
      } else {
        console.log('no_window.AlipayJSBridge')
        // _this.getCompanyList()
      }
    },

    onCurrentCityClick(e, event) {
      console.log(e, event.target, 'onCurrentCityClick')
      if (e == '定位失败') {
        this.getLocationJSAPINew()
      } else {
        if (window.sensors) {
          window.sensors.quick('trackAllHeatMap', event.target, {
            $title: '总行_食堂_城市选择',
            firefly_click_area: '总行_食堂_城市选择_选择城市',
            firefly_click_name: this.city
          })
        }
        const cityInfo = {
          city: this.city,
          cityCode: this.cityCode
        }
        localStorage.setItem('cityInfo', JSON.stringify(cityInfo))
        this.$router.go(-1)
      }
    },
    onCityClick(e, event) {
      console.log(event.target, 'event')
      // 萤火埋点
      if (window.sensors) {
        window.sensors.quick('trackAllHeatMap', event.target, {
          $title: '总行_食堂_城市选择',
          firefly_click_area: '总行_食堂_城市选择_选择城市',
          firefly_click_name: e.name
        })
      }

      // 将本次点击省市存下来
      if (this.historyCity.findIndex((item) => item.name == e.name) == -1) {
        this.historyCity.unshift(
          this.cityList.find((item) => item.name == e.name)
        )
      }

      if (this.historyCity.length > 9) {
        this.historyCity.pop()
      }

      // 记录历史记录
      const historyInfo = this.historyCity
      localStorage.setItem('historyCity', JSON.stringify(historyInfo))
      const cityInfo = {
        city: e.name,
        cityCode: e.code
      }
      console.log(e, cityInfo, 'e')
      localStorage.setItem('cityInfo', JSON.stringify(cityInfo))
      this.$router.go(-1)
      // console.log(app.globalData)
    },
    onShareAppMessage() {
      // 返回自定义分享信息
      return {
        title: '食堂',
        desc: '在线充值、扫码取餐、预订配送、在线管理、人脸支付',
        path: 'https://wx.abchina.com/webank/main-view/openTagForZHMarketingSes?id=%2BwenJ0hvCug%3D'
      }
    },
    openPopup() {
      this.isShowH5Pop = true
    },
    // 从设置页或其他APP跳转回到此页面
    handleVisibilityChange() {
      console.log(document.visibilityState, 'cityPage')
      if (document.visibilityState === 'visible') {
        if (localStorage.getItem('cityLocationPermission')) {
          Toast.loading({
            duration: 0, // 持续展示 toast
            message: '处理中...'
          })
          const _this = this
          window.AlipayJSBridge.call('location', {}, function(result) {
            const res = result
            console.log(res, 'res获取222')
            // 获取用户当前位置省市信息
            if (res.error) {
              // 定位失败 添加默认城市缓存 避免下次进入仍然调取定位
              // 申请后仍然失败
              localStorage.setItem('locationPermission', true)
              _this.cityName = '定位失败'
              _this.city = '开启定位'
              _this.cityCode = '110100'
              _this.getCityList()
            } else {
              // 定位成功
              let cityCode = Number(res.adCode)
              cityCode = parseInt(cityCode / 100) * 100
              console.log(999, cityCode)
              _this.cityName = res.city
              _this.city = res.city
              _this.cityCode = cityCode
              localStorage.removeItem('locationPermission')
              _this.getCityList()
            }
          })
        }
      } else {
        // onPagePause();
      }
    }
  },
  onHide() {
    // H5中 除了首页其他页面不需要展示右上角的点点点
    // #ifdef H5
    if (window && window.AlipayJSBridge) {
      window.AlipayJSBridge.call('hideOptionMenu')
    } else {
      console.log('hideOptionMenu方法没有获取成功')
    }
    // #endif
  }
}
</script>

<style scoped lang="less">
page {
  height: 100%;
}

.city-select {
  height: 100%;
  padding: 0 8px;
  background-color: #fff;
}

.scroll-container {
  -webkit-overflow-scrolling: touch;
}

.scroll-container::-webkit-scrollbar {
  display: none;
  /* 隐藏滚动条 */
}

.search-header {
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.location {
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
}

.location-city {
  color: #333333;
  font-size: 32px;
}

.search-content {
  flex: 3;
}

.list-alphabet {
  display: flex;
  flex-direction: column;
  justify-content: center;
  //设置字母表的位置在靠右，宽度，和距离顶部的距离
  position: fixed;
  right: 0;
  top: 430px;
  // bottom: 0;
  width: 50px;

  .item {
    // 设置字母居中和间距
    font-size: 26px;
    line-height: 28px;
    text-align: center;
    color: #909090;
  }
}

.list-header {
  line-height: 30px;
  background-color: #fff;
  color: #999999;
  margin-left: 6px;
  font-size: 16px;
}

.list-header1 {
  line-height: 30px;
  background-color: #fff;
  color: #999999;
  margin-left: 6px;
  font-size: 14px;
}

.history-list {
  /* margin-left: 6px; */
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.history-item {
  /* background-color: #f1f1f1; */
  line-height: 18px;
  padding: 7px 15px;
  border-radius: 17.5px;
  margin: 5px 6px;
  border: #c4c4c4 0.5px solid;
  max-width: 620rpx;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.am-list-header {
  /* background-color: #f7f7f7; */
  margin-top: 10px;
}

.address-item {
  min-height: 98rpx;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-bottom: 1px solid #f1f1f1;
  padding: 0 32rpx;
}

.item-title {
  width: 140rpx;
  color: #4d4c4c;
  font-size: 28rpx;
  height: 98rpx;
  line-height: 98rpx;
}

.item-content {
  width: 520rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 28rpx;
  height: 98rpx;
  line-height: 98rpx;
  color: #4d4c4c;
}

.am-tabs-bar {
  z-index: 999;
}

.am-tabs-bar-title {
  margin-right: var(--am-tabs-title-marginRight, 24px);
}

.am-tabs-bar-title__noMargin {
  margin-right: 0;
}

.list-empty {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 260rpx;
}

/* 地区级联选择器 */

.picker-view {
  width: 100%;
  display: flex;
  background-color: #fff;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  bottom: 0rpx;
  left: 0rpx;
}

.picker-item {
  line-height: 70rpx;
  margin-left: 5rpx;
  margin-right: 5rpx;
  text-align: center;
}

.picker-view__pane {
  height: 100rpx;
  width: 100%;
  padding: 20rpx 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
}

.picker-view__pane text {
  font-size: 30rpx;
}

.pick-view__group {
  width: 96%;
  height: 480rpx;
}

.tab-content {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
  box-sizing: border-box;
  /* 如果 swipeable="{{true}}"，需要增加 height */
  /* height: 350px; */
  /* 为了体现 stickyBar 的作用而增加的 tab-content 的高度 */
  height: 50vh;
}

.dyt-list {
  margin-top: 0;
}

.dyt-list .am-list-item-thumb {
  border-radius: 5px;
}

.dyt-list .am-list-brief {
  color: #909090;
  font-size: 14px;
}

.am-list-sticky {
  position: sticky;
  top: 0;
  z-index: 2;
}

.am-popup-mask {
  z-index: 999;
}

.am-popup-bottom {
  z-index: 999;
}

.am-alphabet {
  z-index: 2021;
  right: 0.5%;
}

/* @media (max-height: 800px) {
  .am-alphabet {
    display: none;
  }
} */

.city-list {
  padding: 20px;
  font-size: 32px;
  line-height: 80px;

  .city-header {
    border-bottom: 1px solid #f4f4f4;
  }

  .city-item {
    border-bottom: 1px solid #f4f4f4;
  }
}

.location-header {
  color: #666666;
  margin-bottom: 18px;
}

.location-list {
  display: flex;
  // justify-content: space-between;
  flex-wrap: wrap;
}

.location-item {
  text-align: center;
  line-height: 30px;
  padding: 15px 30px;
  border-radius: 40px;
  /* margin: 5px 6px; */
  border: #c4c4c4 0.5px solid;
  width: 35%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin: 8px;
}

.location-img {
  position: relative;
  top: 2px;
  right: 3px;
  height: 26px;
  width: 26px;
}

@media only screen and (min-width: 700px) {
  /* 对于折叠屏，通常需要特定的样式来适配 */
  .city-list {
    padding: 10px;
    font-size: 32px;
    line-height: 70px;

    .city-header {
      border-bottom: 1px solid #f4f4f4;
    }

    .city-item {
      border-bottom: 1px solid #f4f4f4;
    }
  }

  .list-alphabet {
    display: flex;
    flex-direction: column;
    justify-content: center;
    //设置字母表的位置在靠右，宽度，和距离顶部的距离
    position: fixed;
    right: 0;
    top: 430px;
    // bottom: 0;
    width: 50px;

    .item {
      // 设置字母居中和间距
      font-size: 26px;
      line-height: 28px;
      text-align: center;
      color: #909090;
    }
  }
}
</style>
